﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Vit.Common.Extensions
{
    public static class EnumerableExtensions
    {
        public static void ForEach<T>(this IEnumerable<T> collection, Action<T, int> action)
        {
            int idx = 0;
            foreach (T ele in collection)
                action(ele, idx++);
        }

        public static void ForEach<T>(this IEnumerable<T> collection, Func<T, int, bool> action)
        {
            int idx = 0;
            foreach (T ele in collection)
            {
                bool result = action(ele, idx++);
                if (!result)
                    return;
            }
        }

        public static int ElementIndex<T>(this IEnumerable<T> collection, T obj)
        {
            int idx = -1;
            foreach (T ele in collection)
            {
                idx++;
                if (ele.Equals(obj))
                    return idx;
            }
            return -1;
        }

        public static int ElementIndex<T>(this IEnumerable<T> collection, Predicate<T> predict)
        {
            int idx = -1;
            foreach (T ele in collection)
            {
                idx++;
                if (predict(ele))
                    return idx;
            }
            return -1;
        }

        public static IEnumerable<U> Cast<T, U>(this IEnumerable<T> collection, Func<T, U> converter)
        {
            foreach (T obj in collection)
                yield return converter(obj);
        }

        public static IEnumerable<T> Merge<T>(this IEnumerable<T> collection, IEnumerable<T> targets)
        {
            List<T> list = new List<T>();
            list.AddRange(collection);
            foreach (T obj in targets)
                if (list.Contains(obj) == false)
                    list.Add(obj);
            return list;
        }
    }
}
